<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ttp
 * Date: 5/7/11
 * Time: 1:10 PM
 * To change this template use File | Settings | File Templates.
 */
 
class Map_PointController extends App_Controller_Action
{
    /**
     * @var Map_Model_Point
     */
    private $_model;

    public function init()
    {
        parent::init();
        $this->_model = new Map_Model_Point();
    }

    public function indexAction()
    {
        $this->view->headScript()->appendFile('http://maps.google.com/maps/api/js?sensor=true');
        $this->view->headScript()->appendFile(BASE_URL . '/js/app/map/point.js');
        $this->view->headScript()->appendFile(BASE_URL . '/js/app/map/point_init.js');
        $this->view->headLink()->appendStylesheet(BASE_URL . '/css/app/map/map.css');

        $this->view->headScript()->appendFile(BASE_URL . '/js/lib/jqgrid/js/i18n/grid.locale-en.js');
        $this->view->headScript()->appendFile(BASE_URL . '/js/lib/jqgrid/js/jquery.jqGrid.min.js');
        $this->view->headLink()->appendStylesheet(BASE_URL . '/js/lib/jqgrid/css/ui.jqgrid.css');

        $this->view->formPoint = new Map_Form_Point();
        $this->render();
    }

    public function listAction()
    {
        $rows = $this->_model->fetchAll();
        $this->_helper->json->sendJson(array('data' => $rows->toArray()));
    }

    public function listGridAction()
    {
        $params = $this->_getAllParams();
        $rows = $this->_model->getList($params);
        $cnt = $this->_model->getCnt($params);

        $this->_helper->json->sendJson(array(
            'records' => $cnt,
            'page' => $params['page'],
            'total' => ceil($cnt / $params['rows']),
            'rows' => $rows
        ));
    }

    public function saveAction()
    {
        $form = new Map_Form_Point();
        $params = $this->_getAllParams();
        if (!$form->isValid($params)) {
            $errors = $form->getErrorMessages();
            $this->sendErrors($errors);
            return;
        }
        $values = $form->getValues();
        if ($params['point_pid']) {
            $row = $this->_model->find($params['point_pid'])->current();
            $row->setFromArray($values);
            $row->save();
        } else {
            $this->_model->insert($values);
        }
        $this->sendSuccess();
    }

    public function loadAction()
    {
        $id = $this->_getParam('id', 0);
        if (!$id) {
            $this->sendErrors('Incorrect id');
        }
        $row = $this->_model->find($id)->current();
        $this->_helper->json->sendJson($row->toArray());
    }

    public function deleteAction()
    {
        $id = $this->_getParam('id');
        $where = $this->_model->select()->where('point_pid = ?', $id);
        $this->_model->delete($where);
        $this->sendSuccess();
    }
}